package vip.xiaonuo.bi.modular.datasource.provider;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import vip.xiaonuo.bi.core.datasource.common.AbstractDataSourceConfig;
import vip.xiaonuo.bi.core.datasource.enums.DataSourceConfigType;
import vip.xiaonuo.bi.core.datasource.enums.DataSourceTypeEnum;
import vip.xiaonuo.bi.modular.datasource.param.DatasourceAddParam;
import vip.xiaonuo.common.exception.CommonException;

@Component
public class BuildDataSourceConfigService {


    public AbstractDataSourceConfig buildDataSourceConfig(DatasourceAddParam datasourceAddParam) {
        // 根据数据源类型和版本获取对应的DataSourceTypeEnum 的val值 ==》DataSourceType 与 DataSourceTypeEnum  中的val 值一一对应
        DataSourceTypeEnum typeEnum = DataSourceTypeEnum.typeVersionOf(datasourceAddParam.getDataType(), datasourceAddParam.getDataVersion());

        // 构造数据连接配置
        JSONObject jsonObject = string2JSONObject(datasourceAddParam.getDataJsonConfig());
        DataSourceConfigType dataSourceConfigType =DataSourceConfigType.getDataSourceConfigType(typeEnum.getVal());
        // 解析参数dataJsonConfig.dataJsonConfig:数据源表单填写数据Json配置字符串
        AbstractDataSourceConfig dataSourceConfig = dataSourceConfigType.getDataSourceConfig(jsonObject, null);
        // todo 检验预制认证信息

        return dataSourceConfig;
    }

    /**
     * 字符串转化为JSONObject对象
     * @param dataJsonStr
     * @return
     */
    private static JSONObject string2JSONObject(String dataJsonStr) {
        if (StringUtils.isBlank(dataJsonStr)) {
            throw new CommonException("数据源信息为空");
        }
        try {
            return JSONObject.parseObject(dataJsonStr);
        } catch (Exception e) {
            throw new CommonException(String.format("转化json格式异常：%s", e.getMessage()), e);
        }
    }
}
